import React, { useEffect, useState } from 'react';
import { Divider, List, PullRefresh, Toast } from 'react-vant';
import { ShoppingCartO, OrdersO, Completed, BalanceListO } from '@react-vant/icons';
import StatsCard from '../../components/StatsCard';
import OrderCard from '../../components/OrderCard';
import './Home.css';
import OrdersApi from '@/apis/ordersApi';
import { promptResult } from '@/utils/common';
import statisticsApi from '@/apis/statisticsApi';

const limit = 10;

const Home: React.FC = () => {
  const [stats, setStats] = useState<ResponseStatisticsDto | null>(null);
  const [orders, setOrders] = useState<ResponseOrdersDto[]>([]);
  const [page, setPage] = useState(1);
  const [finish, setFinish] = useState(false);
  const [loading, setLoading] = useState({
    stats: true,
    orders: true,
  });

  useEffect(() => {
    const fetchData = async () => {
      const res = await statisticsApi.getHomeStatistics();
      setStats(res.data);
    };
    fetchData();
  }, []);

  const handleAcceptOrder = async (orderId: number) => {
    promptResult(
      OrdersApi.takeOrder(orderId),
      () => {},
      () => {
        let temp: ResponseOrdersDto[] = [...orders];
        temp.find((d) => d.id === orderId)!.status = 1;
        setOrders(temp);
      }
    );
  };

  const handleShipment = async (orderId: number) => {
    promptResult(
      OrdersApi.shipment(orderId),
      () => {},
      () => {
        let temp: ResponseOrdersDto[] = [...orders];
        temp.find((d) => d.id === orderId)!.status = 2;
        setOrders(temp);
      }
    );
  };

  const loadMore = async () => {
    const res: ResponseApiDto = await OrdersApi.getOrdersPagination(
      page,
      limit,
      undefined,
      [0, 1, 2]
    );
    if (res.status >= 0) {
      setOrders([...orders, ...res.data.data]);
      setPage((prev) => prev + 1);
      if (res.data.data.length < limit) {
        setFinish(true);
      }
    }
    setLoading({ ...loading, orders: false });
  };

  const handleRefresh = async () => {
    setLoading({ ...loading, orders: true });
    const res: ResponseApiDto = await OrdersApi.getOrdersPagination(1, limit, undefined, [0, 1, 2]);
    if (res.status >= 0) {
      setOrders(res.data.data);
      if (res.data.data.length < limit) {
        setFinish(true);
      }
    }
    setLoading({ ...loading, orders: false });
  };

  return (
    <div className="content">
      {/* 统计数据 */}
      <div className="stats-section">
        <div className="grid-container">
          <StatsCard
            title="今日订单"
            value={stats?.todayOrderCount != null ? stats?.todayOrderCount : '-'}
            icon={<OrdersO fontSize={20} />}
            color="#1989fa"
          />
          <StatsCard
            title="待处理"
            value={stats?.awaitActionOrderCount != null ? stats?.awaitActionOrderCount : '-'}
            icon={<ShoppingCartO fontSize={20} />}
            color="#ff976a"
          />
          <StatsCard
            title="已完成"
            value={stats?.todayFinishedOrderCount != null ? stats?.todayFinishedOrderCount : '-'}
            icon={<Completed fontSize={20} />}
            color="#07c160"
          />
          <StatsCard
            title="今日收入"
            value={stats?.todaySumSales != null ? `¥${stats.todaySumSales.toFixed(2)}` : '-'}
            icon={<BalanceListO fontSize={20} />}
            color="#ee0a24"
          />
        </div>
      </div>

      <Divider>待处理订单</Divider>

      {/* 订单列表 */}
      <PullRefresh onRefresh={handleRefresh}>
        <List
          onLoad={loadMore}
          finished={finish}
          finishedText="没有更多了"
          className="orders-section"
        >
          {orders.map((order) => (
            <OrderCard
              key={order.id}
              order={order}
              onAccept={handleAcceptOrder}
              onShipment={handleShipment}
            />
          ))}
        </List>
      </PullRefresh>
    </div>
  );
};

export default Home;
